package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author SunSun
 * @date 2021/11/3
 */

@Service
public class ManagerService {

//    @Autowired
//    private AdminMapper adminMapper;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo>  list=userInfoApi.findAll(page,pagesize);
        List<UserInfo> records = list.getRecords();
        for (UserInfo record : records) {
            String key=Constants.USER_FREEZE+record.getId();
            if(redisTemplate.hasKey(key)){
                record.setUserStatus("2");
            }
        }
        return new PageResult(page,pagesize,list.getTotal(),list.getRecords());
    }

    public ResponseEntity findById(Long userId) {
        UserInfo byid = userInfoApi.findByid(userId);
        String key=Constants.USER_FREEZE+userId;
        if(redisTemplate.hasKey(key)){
            byid.setUserStatus("2");
        }
        return ResponseEntity.ok(byid);
    }

    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {

        return videoApi.finByUserId(page,pagesize,uid);
    }

    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer states) {

        PageResult result=movementApi.findByUserId(page,pagesize,uid,states);

        List<Movement> items = (List<Movement>) result.getItems();
        if(CollUtil.isEmpty(items)){
            return  new PageResult();
        }

        List<Long> userId = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);

        List<MovementsVo> vos=new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = map.get(item.getUserId());
            if (userInfo!=null){
                MovementsVo init = MovementsVo.init(userInfo, item);
                vos.add(init);
            }
        }
        result.setItems(vos);
        return result;
    }

    //用户冻结
    public Map userFreeze(Map params) {
        //1.构造key
        String userId=params.get("userId").toString();
        String key=Constants.USER_FREEZE+userId;

        Integer freezingTime= Integer.valueOf(params.get("freezingTime").toString()) ;

        int days=0;
        if(freezingTime==1){
            days=3;
        }else if (freezingTime==2){
            days=7;
        }

        String value=JSON.toJSONString(params);

        if(days>0){
            redisTemplate.opsForValue().set(key,value,days,TimeUnit.MINUTES);
        }else {
            redisTemplate.opsForValue().set(key,value);
        }
        Map retMap=new HashMap();
        retMap.put("message","冻结成功");
        return retMap;
    }

    public Map userUnfreeze(Map params) {
        //1.构造key
        String userId=params.get("userId").toString();
        String key=Constants.USER_FREEZE+userId;

        redisTemplate.delete(key);

        Map retMap=new HashMap();
        retMap.put("message","解冻成功");
        return retMap;
    }

    public MovementsVo findByidMovement(String movementId) {
        Movement movement = movementApi.findOne(movementId);
        if (movement!=null){
            UserInfo userInfo = userInfoApi.findByid(movement.getUserId());
            if (userInfo!=null){
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                return vo;
            }
        }
            return null;
    }

    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        List<Comment> list=commentApi.findComments(movementId,CommentType.COMMENT,page,pagesize);

        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }

        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(userIds, null);

        List<CommentVo> lists=new ArrayList<>();

        for (Comment comment : list) {
            UserInfo userInfo = byIds.get(comment.getUserId());
            if(userInfo!=null){
                CommentVo commentVo=CommentVo.init(userInfo,comment);
                commentVo.setUserId(userInfo.getId());
                lists.add(commentVo);
            }
        }

        return new PageResult(page,pagesize,0l,lists);
    }
}
